package com.gz.mylife.im;

import java.util.Observable;
import java.util.Observer;

import android.util.Log;
import android.util.SparseArray;

/**
 * 在jpushReceiver 中处理并保存数据，然后通过观察者更新到聊天会话
 * 待完善：不管是聊天室还是私信，给他们注册独立的通道id，收到消息后指定发送，目前需要接收端判断
 * @author linwenming
 *
 */
public class MessageChannel{

	public static final String TAG = "MessageChannel";
	
	public static final int MESSAGE = 101;
	public static final int SESSION = 102;
	public static final int NOTIFY = 103;
	public static final int RMESSAGE = 104;
	public static final int VERSION = 105;
	
	private static final MessageChannel mMessageChannel = new MessageChannel();
	public SparseArray<MessageObservable> mChannels = new SparseArray<MessageObservable>();
	
	private MessageChannel() {
	}
	
	public static MessageChannel get(){
		return mMessageChannel;
	}
	
	public void sendMessage(Object value){
		send(MESSAGE, value);
	}
	
	public void sendSession(Object value){
		send(SESSION, value);
	}
	
	public void sendNotify(Object value){
		send(NOTIFY, value);
	}

	public void sendRoomMessage(Object value){
		send(RMESSAGE, value);
	}
	
	public void sendVersion(Object value){
		send(VERSION, value);
	}
	
	private void send(int channel,Object value){
		MessageObservable observable = mChannels.get(channel);
		if(observable!= null){
			Meta data = new Meta();
			data.msgType = channel;
			data.data = value;
			observable.send(data);
		} else {
			Log.w(TAG, "没有注册观察者:"+channel);
		}
	}
	
	public void register(int channel,Observer observer){
		
		MessageObservable observable = mChannels.get(channel);
		if(observable == null){
			observable = new MessageObservable();
			mChannels.put(channel, observable);
		}
		observable.addObserver(observer);
	}
	
	public void unregister(int channel,Observer observer){
		MessageObservable observable = mChannels.get(channel);
		if(observable != null){
			observable.deleteObserver(observer);
		}
	}
	
	static class MessageObservable extends Observable{
		
		public void send(Object value){
			setChanged();  
			notifyObservers(value);
		}
	}
	
	public static class Meta {
		public int msgType;
		public Object data;
	}
}
